//
//  AuthenMiniLegalPhotoVM.swift
//  kxf
//
//  Created by Mac on 2024/3/7.
//   店主信息页面照片

import Foundation
import UIKit
import MCToast

class AuthenMiniLegalPhotoVM: UIView {
    
    let selfHeight = AuthenPhotoVM().selfHeight*2
    
    var controller = WHBaseViewVC()
    private var imgSourceType = PHOTOTYPE.idCardFront
    var imgType = ""
    
    var idOcrFrontBlock:((NSDictionary)->())?
    var idOcrBackBlock:((NSDictionary)->())?
    var bankOcrFrontBlock:((NSDictionary)->())?
    
    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: 0, y: frame.origin.y, width: SCREEN_WIDHT, height: selfHeight))
        self.backgroundColor = .white
        self.isUserInteractionEnabled = true
        //authen_photo_id_front
        initUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var idCardFrontPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0  ))
        vm.titleLabel.text = "点击上传身份证人像面"
        vm.addIconImg.image = UIImage.init(named: "authen_photo_id_front")
        vm.photoBlock = {()in
            self.imgSourceType = .idCardFront
            self.imgType = "idCardFront"
            self.takePickture()
        }
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .idCardFront)
        }
        return vm
    }()
    lazy var idCardBackPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: SCREEN_WIDHT*0.5, y: 0, width: 0, height: 0  ))
        vm.titleLabel.text = "点击上传身份证国徽面"
        vm.addIconImg.image = UIImage.init(named: "authen_photo_id_back")
        vm.photoBlock = {()in
            self.imgSourceType = .idCardBack
            self.imgType = "idCardBack"
            self.takePickture()
        }
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .idCardBack)
        }
        return vm
    }()
    lazy var bankCardPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: 0, y: AuthenPhotoVM().selfHeight, width: 0, height: 0  ))
        vm.titleLabel.text = "银行卡卡号照"
        vm.photoBlock = {()in
            self.imgSourceType = .bankFront
            self.imgType = "bankCardFront"
            self.takePickture()
        }
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .bankFront)
        }
        return vm
    }()
    lazy var idCardInHandPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: SCREEN_WIDHT*0.5, y: AuthenPhotoVM().selfHeight, width: 0, height: 0  ))
        vm.titleLabel.text = "手持身份证照"
        vm.photoBlock = {()in
            self.imgSourceType = .idCardInHand
            self.imgType = "idCardInHand"
            self.takePickture()
        }
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .idCardInHand)
        }
        return vm
    }()
    lazy var sampleAlertVm : AuthenPhotoSampleAlertVM = {
        let vm = AuthenPhotoSampleAlertVM.init(frame: .zero)
        vm.isHidden = true
        return vm
    }()
}

extension AuthenMiniLegalPhotoVM{
    func initUI() {
        addSubview(idCardFrontPhotoVm)
        addSubview(idCardBackPhotoVm)
        addSubview(bankCardPhotoVm)
        addSubview(idCardInHandPhotoVm)
        
        UIApplication.shared.keyWindow?.addSubview(sampleAlertVm)
    }
    func updateUIForRefuse() {
        idCardFrontPhotoVm.setImgUrl(urlstring: "\(AuthenMiniMsgModel.shareInstance.photoImgUrlIdCardFront)")
        idCardBackPhotoVm.setImgUrl(urlstring: "\(AuthenMiniMsgModel.shareInstance.photoImgUrlIdCardBack)")
        idCardInHandPhotoVm.setImgUrl(urlstring: "\(AuthenMiniMsgModel.shareInstance.photoImgUrlIdCardInhand)")
        bankCardPhotoVm.setImgUrl(urlstring: "\(AuthenMiniMsgModel.shareInstance.photoImgUrlBankCardFront)")
    }
    func setReadMode() {
//        idCardFrontPhotoVm.imgView.isUserInteractionEnabled = false
//        idCardBackPhotoVm.imgView.isUserInteractionEnabled = false
//        idCardInHandPhotoVm.imgView.isUserInteractionEnabled = false
//        bankCardPhotoVm.imgView.isUserInteractionEnabled = false
        idCardFrontPhotoVm.setReadMode()
        idCardBackPhotoVm.setReadMode()
        idCardInHandPhotoVm.setReadMode()
        bankCardPhotoVm.setReadMode()
    }
}

extension AuthenMiniLegalPhotoVM:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    @objc func takePickture(){
        let alertController=UIAlertController(title: "请选择照片来源", message: nil, preferredStyle: .actionSheet)

        let cancel=UIAlertAction(title:"取消", style: .cancel, handler: nil)
        
        let takingPictures=UIAlertAction(title:"拍照", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                if self.imgSourceType == .idCardFront {
                    let vc = DXIDCardCameraController.init(type: DXIDCardType.front)
                    vc.delegate = self
                    vc.modalPresentationStyle = .fullScreen
                    self.controller.present(vc, animated: true, completion: nil)
                }else if self.imgSourceType == .idCardBack {
                    let vc = DXIDCardCameraController.init(type: DXIDCardType.reverse)
                    vc.delegate = self
                    vc.modalPresentationStyle = .fullScreen
                    self.controller.present(vc, animated: true, completion: nil)
                }else if self.imgSourceType == .bankFront {
                    let vc = DXIDCardCameraController.init(type: DXIDCardType.bank)
                    vc.delegate = self
                    vc.modalPresentationStyle = .fullScreen
                    self.controller.present(vc, animated: true, completion: nil)
                }else{
                    let  cameraPicker = UIImagePickerController()
                    cameraPicker.delegate = self
                    cameraPicker.sourceType = .camera
                    //在需要的地方present出来
                    self.controller.present(cameraPicker, animated: true, completion: nil)
                }
            } else {
                print("不支持拍照")
            }
        }
        let photoPictures=UIAlertAction(title:"相册", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = true
                cameraPicker.sourceType = .photoLibrary
                //在需要的地方present出来
                self.controller.present(cameraPicker, animated: true, completion: nil)
            } else {
                print("不支持拍照")
            }
        }
        
        alertController.addAction(cancel)
        alertController.addAction(takingPictures)
        alertController.addAction(photoPictures)
        
        self.controller.present(alertController, animated:true, completion:nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        print("获得照片============= \(info)")
        self.controller.dismiss(animated: true, completion: nil)
        MCToast.mc_loading()
        let image = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage)!
        let imageData = WHRequestTools.compressImage(toData: image)
//        let imageData = image.jpegData(compressionQuality: 1.0)
        
        DSImageUploader.shared.uploadImages(_image: imageData!,imgType: "\(self.imgType)") { text, value in
            DLLog(message: "\(text)")
            DLLog(message: "\(value)")
            MCToast.mc_remove()
            if value == true{
                if self.imgSourceType == .idCardFront || self.imgSourceType == .idCardBack{
                    self.sendOcrIdCardRequest(urlString: "\(text)")
                }else if self.imgSourceType == .bankFront{
                    self.sendOcrBankCardRequest(urlString: "\(text)")
                }else{
                    self.idCardInHandPhotoVm.setImgUrl(urlstring: "\(text)")
                    AuthenMiniMsgModel.shareInstance.photoImgUrlIdCardInhand = "\(text)"
                }
            }else{
                MCToast.mc_text("图片上传失败")
            }
        }
    }
}


extension AuthenMiniLegalPhotoVM : DXIDCardCameraControllerProtocol {
    func cameraDidFinishShootWithCameraImage(image: UIImage) {
        let imageData = WHRequestTools.compressImage(toData: image)
//        let imageData = image.jpegData(compressionQuality: 1.0)
        MCToast.mc_loading()
        DSImageUploader.shared.uploadImages(_image: imageData!,imgType: "\(self.imgType)") { text, value in
            DLLog(message: "\(text)")
            DLLog(message: "\(value)")
            MCToast.mc_remove()
            if value == true{
                if self.imgSourceType == .idCardFront || self.imgSourceType == .idCardBack{
                    self.sendOcrIdCardRequest(urlString: "\(text)")
                }else if self.imgSourceType == .bankFront{
                    self.sendOcrBankCardRequest(urlString: "\(text)")
                }
            }else{
                MCToast.mc_text("图片上传失败")
            }
        }
    }
}
extension AuthenMiniLegalPhotoVM{
    func sendOcrIdCardRequest(urlString:String) {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_OCR_idCard)?url=\(urlString)", vc: self.controller) { responseObject in
            DLLog(message: "\(responseObject)")
            if responseObject["code"]as? Int ?? 0 == 200{
                if self.imgSourceType == .idCardFront{
                    let data = responseObject["data"]as? NSDictionary ?? [:]
                    let result = data["result"]as? NSDictionary ?? [:]
                    
                    if self.idOcrFrontBlock != nil{
                        self.idOcrFrontBlock!(result["result"]as? NSDictionary ?? [:])
                    }
                    self.idCardFrontPhotoVm.setImgUrl(urlstring: urlString)
                    AuthenMiniMsgModel.shareInstance.photoImgUrlIdCardFront = urlString
                }else if self.imgSourceType == .idCardBack{
                    if self.idOcrBackBlock != nil{
                        let data = responseObject["data"]as? NSDictionary ?? [:]
                        let result = data["result"]as? NSDictionary ?? [:]
                        self.idOcrBackBlock!(result["result"]as? NSDictionary ?? [:])
                    }
                    self.idCardBackPhotoVm.setImgUrl(urlstring: urlString)
                    AuthenMiniMsgModel.shareInstance.photoImgUrlIdCardBack = urlString
                }
            }else{
                self.controller.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "识别失败，请重新拍摄照片")", viewController: self.controller)
            }
            
        }
    }
    func sendOcrBankCardRequest(urlString:String) {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_OCR_bank)?url=\(urlString)", vc: self.controller) { responseObject in
            DLLog(message: "\(responseObject)")
            if responseObject["code"]as? Int ?? 0 == 200{
                if self.bankOcrFrontBlock != nil{
                    let data = responseObject["data"]as? NSDictionary ?? [:]
                    let result = data["result"]as? NSDictionary ?? [:]
                    self.bankOcrFrontBlock!(result["result"]as? NSDictionary ?? [:])
                }
                
                self.bankCardPhotoVm.setImgUrl(urlstring: urlString)
                AuthenMiniMsgModel.shareInstance.photoImgUrlBankCardFront = urlString
            }else{
                self.controller.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "识别失败，请重新拍摄照片")", viewController: self.controller)
            }
        }
    }
}
